package system

import (
	"context"
	"slices"
	"strconv"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteDeptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	deptModel model.SysDeptModel
}

func NewDeleteDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteDeptLogic {
	return &DeleteDeptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
	}
}

func (l *DeleteDeptLogic) DeleteDept(req *types.IdRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	// 删除部门连带的所有的部门
	err = auth.HasPermission(l.menuModel,l.ctx,"system:dept:remove")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	roles,err := auth.GetRoles(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}
	authinfo,_ := auth.GetAuth(l.ctx)
	owndeptId,err := strconv.Atoi(authinfo.DeptId)
	if err != nil {
		return nil,errorx.TypeTransError
	}
	// 查询到部门及其所属子部门进行删除
	needDelDepts,err := l.deptModel.GetListBase(l.ctx,nil,req.Id,false)
	if err != nil {
		return nil,errorx.SqlSearchError
	}
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		ableManageDepts,err := getDepts(l.ctx,int64(owndeptId),roles,l.deptModel,&types.ListDeptRequest{})
		if err != nil {
			return nil,errorx.NewBizError(500,"部门信息查询失败")
		}
		for _,val := range needDelDepts {
			isHas := false
			isHas = slices.ContainsFunc(ableManageDepts,func(n *types.Dept)bool{
				return n.DeptId == val.DeptId
			})
			if !isHas {
				return nil,errorx.Unauthorized
			}
		}
	}
	deptIds := make([]*int64,0)
	for _,val := range needDelDepts {
		deptIds = append(deptIds, &val.DeptId)
	}
	err = l.deptModel.DeleteByIds(l.ctx,nil,deptIds)
	return &types.CommonResponse{
		Status: 200,
		Msg: "删除成功",
	},err
}
